var async = require('async');
var path = require('path');
var fs = require('fs');
var admin = './api/admin.json';

exports.isLogin = function (req, res, next) {
    var user = req.session.user;
	if (!user) {
		return res.redirect("/admin/login");
	}
	next();
};

exports.logout = function (req, res) {
    req.session.destroy(function(err) {
        if(err){
            return res.send({'status': 0, 'msg': '退出登录失败!'});
        }
        
        res.clearCookie('keydone');
        res.redirect('/');
    });
};

exports.postLogout = function (req, res) {
    var action = req.body.action;
    if (action == 'logout') {
        req.session.destroy(function(err) {
            if(err){
                return res.send({'status': 0, 'msg': '退出登录失败!'});
            }
            
            res.clearCookie('keydone');
            res.redirect('/');
        });
    }
}

exports.postLogin = function (req, res) {
    var params = req.body, username = params.account,
        password = params.password;
    async.parallel([
        function (cb) {
            var _admin = JSON.parse(fs.readFileSync(admin));
            cb(null, _admin);
        }
    ], function (error, results) {
        var admin = results[0];
        if (username == admin.account && password == admin.password) {
            var user = { username: username };
            req.session.regenerate(function(err) {
                if(err){
                    return res.send({'status': 0, 'msg': 'fail'});                
                }
                //登录成功就记录session
                req.session.user=user;
                res.send({'status': 1, 'msg': 'ok'});
            });
        } else {
            res.send({
                'status': 0,
                'msg': '密码或账户错误!'
            });
        }
    });
}

exports.admin = function (req, res) {
    res.render('admin/admin');
}

exports.articles = function (req, res) {
    
}